#!/bin/bash
#
######################################################
# find-vi wrapper


EXT=".scala"
EXE="vi"

argc=0
args=("$@")

# head limit
ffh=20

fff=""
ffn=""
ffa=()

# file find option
ff_d="*"
ff_r="."
ff_t="f"
ff_c="*$EXT"

#===================================================================
# arguments process
# if given a valid file, try to open it
# if given a number, try to open file of ffa[number]
# if given -d with valid directry, try to find all .$EXT files inisde
# if given -d with invalid directory, try to list all similar directories
# if given .*, use it as filter for target file, default is .scala
# in any case, if valid files founded, you can select one to open 
#
# if given -h, modify the list count limitation ($ffh)
#===================================================================
skip=0
for argv in $*
do
  let "argc+=1"
  [[ $skip == 1 && $argv != "-"* ]] && skip=0 && continue
  [[ -f "$argv" ]] && fff=$argv && continue
  [[ $argv == "-h" ]] && ffh=${args[$argc]} && skip=1 && continue
  [[ $argv =~ ^[0-9]+$ ]] && ffn=$argv && continue
  [[ ${argv} =~ ^\.[a-zA-Z]+$ ]] && ff_c="*$argv" && continue

  if [[ $argv == "-d" ]]; then
   if [[ -d "${args[$argc]}" ]]; then
     ff_r=${args[$argc]}
     ff_d="*"
   else
     ff_d="*${args[$argc]}*"
     ff_c="*"
     ff_t="d"
   fi
  fi
done

if [[ "$fff" != "" && -f "$fff" ]]; then
  $EXE $fff
else
  fn=0
  fs=$ffh
  files=$(find $ff_r -type $ff_t -ipath "$ff_d" -iname "$ff_c" | xargs -i echo {})
  #files=$(find $ff_r -type $ff_t -ipath "$ff_d" -iname "$ff_c" -exec echo {} \;)

  for ff in $files
  do
    [[ "$ff" != "." ]] && echo $fn : $ff
    ffa+=($ff)
    let fn+=1
    if [[ "$fn" == "$fs" ]]; then
      let fs+=$ffh
      read -p "Select file number or <Enter> to continue: " yon
      [[ $yon =~ ^[0-9]+$ ]] && ffn=$yon && break
    fi
  done  

  if [[ $ffn =~ ^[0-9]+$ ]]; then
    $EXE ${ffa[$ffn]} 
  elif [[ "$fn" == "1" ]]; then
    #echo "fn==1"
    $EXE ${ffa[0]}
  elif [[ "$fn" != "0" && $ff_c != "" ]]; then
    read -p "Select target file number: " yon
    [[ $yon =~ ^[0-9]+$ ]] && $EXE ${ffa[$yon]}
  elif [[ $ff_c != "" ]]; then
    echo -e "No file found of type \"$ff_c\""
  fi
fi
